package gemini.pollux.ui.client.page.content.marketingplan.level.list;

import gemini.basic.model.Level;
import gemini.pollux.ui.client.page.content.marketingplan.level.widget.LevelTableWidget;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.Widget;

public class LevelListView extends Composite implements
		LevelListPresenter.Display {

	@UiTemplate("LevelListView.ui.xml")
	interface MyUiBinder extends UiBinder<Panel, LevelListView> {
	}

	private static final MyUiBinder binder = GWT.create(MyUiBinder.class);

	public LevelListView() {
		initWidget(binder.createAndBindUi(this));
	}

	@UiField
	HTML htmTitle;

	@UiField
	HTML htmInformation;

	@UiField
	LevelTableWidget lvwLevelList;
	
	@Override
	public LevelTableWidget getLevelTableWidget(){
		return lvwLevelList;
	}

	@Override
	public void showLevels(List<Level> levels){
		List<Level> sortedLevels = new ArrayList<Level>(levels.size());
		
		for (Level lv : levels) {
			if(lv.getLevel() == null){
				sortedLevels.add(lv);
				break;
			}
		}
		
		boolean fulled = false;
		boolean found = false;
		
		if (!fulled) {
			for (Level lv : levels) {
				found = false;
				if (lv.getLevel() != null && lv.getLevel().getId() == sortedLevels.get(
						sortedLevels.size() - 1).getId()) {
					sortedLevels.add(lv);
					found = true;
					break;
				}

				if (!found) {
					fulled = true;
				}
			}
		}
		
		lvwLevelList.loadData(levels);
	}

	@Override
	public void initCustom() {
		htmTitle.setHTML("<h3>Level List</h3>");
		htmInformation.setHTML("Levels information");
	}

	@Override
	public Widget asWidget() {
		return this;
	}
}
